// robsingle.js
var app = getApp()
import { formatData, formatTime, formatMoney, outputmoney,} from "../../utils/util.js";
import { showToast } from "../../utils/modal.js";
var date = new Date();
var sliderWidth = 60; 
Page({
  /**
   * 页面的初始数据
   */
  data: {
    weeks_ch: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
    weeks_data: [],
    activeIndex: '',
    weekObj: {
      page: 1,
      time: null,
      limit: ""
    },
    scheduleList: [],
    inputShowed: false,
    inputVal: "",
    tabs: [{ state: "待运输", type: 'ship' }, { state: "未完成", type: 'pending' }, { state: "已完成", type: '' }],
    tabbarList: ["订单","我的"],
    activeIndexs: '',
    sliderOffset: 0,
    sliderLeft: 0,
    type:'ship',
    transportList:[],
    tabbarIndex:0,
    years: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
    user: null,
    money: null,
    yearsList: [],
    monyList: [],
    monyStars: [],
    yearsIndex: parseInt(date.getMonth()),
    pricesList:[]

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let self = this
    self.data.weekObj.time = self.transferDate(date)
    self.getData()
    self.transportList()
    self.data.activeIndex = self.data.weekObj.time
    wx.getSystemInfo({
      success: function (res) {
        self.setData({
          sliderLeft: (res.windowWidth / self.data.tabs.length - sliderWidth) / 2,
          sliderOffset: res.windowWidth / self.data.tabs.length * self.data.activeIndex
        });
      }
    });
    self.dataTime()
  },
  onReady: function () {
    let self = this
    let userObj = wx.getStorageSync('wechat_user')
    console.log(userObj)
    userObj.raty = formatMoney(userObj.raty)
    userObj.amount = formatMoney(userObj.amount, true)
    userObj.security = formatMoney(userObj.security, true)
    userObj.accumulative_count = formatMoney(userObj.accumulative_count, true)
    let moneys = parseFloat(userObj.amount) + parseFloat(userObj.security)
    let moneyPro = outputmoney(moneys)
    self.setData({ money: moneyPro })
    self.setData({ user: userObj })
    self.stars()
  },
  //点击切换
  tabClick: function (e) {
    this.setData({
      sliderOffset: e.currentTarget.offsetLeft,
      activeIndexs: e.currentTarget.id,
      type: e.currentTarget.dataset.type,
      transportList: []
    });

    this.transportList()
  },
  //获取当前一周的日期
  getData: function () {
    var dateArr = []
    var this_day = date.getDay(); //今天是这周的第几天
    var step_s = -this_day + 1; //上周日距离今天的天数（负数表示）
    var step_m = 7 - this_day  // 本周日距离今天的天数
    if (this_day == 0) {
      step_s = -7; // 如果今天是周日
    }
    var thisTime = date.getTime()
    var monday = new Date(thisTime + step_s * 24 * 3600 * 1000)
    var sunday = new Date(thisTime + step_m * 24 * 3600 * 1000)
    var starttime = this.transferDate(monday) //本周一的日期 （起始日期）
    var endtime = this.transferDate(sunday)  //本周日的日期 （结束日期）
    var date1 = this.dataMiddle(starttime)
    var date2 = this.dataMiddle(endtime)
    if (date1 > date2) {
      var tempDate = date1;
      date1 = date2;
      date2 = tempDate;
    }
    console.log(date1.getFullYear(), date2.getFullYear())
    console.log(date1.getDate(), date2.getDate())
    console.log(date1.getMonth(), date2.getMonth())
    var i = 0;
    while (!(date1.getFullYear() == date2.getFullYear()
      && date1.getDate() == date2.getDate())) {
      var dayStr = date1.getDate().toString()
      var dayStr2 = date2.getDate().toString()
      var monStr = date1.getMonth() + 1
      var monStr2 = date2.getMonth() + 1
      if (dayStr.length == 1) {
        dayStr = "0" + dayStr;
      }
      if (dayStr2.length == 1) {
        dayStr2 = "0" + dayStr2;
      }
      if (monStr < 10) {
        monStr = "0" + monStr;
      }
      if (monStr2 < 10) {
        monStr2 = "0" + monStr2;
      }
      var dataObj = { datas: null, day: null, thisDay: null }
      dataObj.datas = date1.getFullYear() + "-" + monStr + "-" + dayStr
      dataObj.day = dayStr
      dataObj.thisDay = this_day
      dateArr[i] = dataObj
      var dataObj2 = { datas: null, day: null, thisDay: null }
      dataObj2.datas = date2.getFullYear() + "-" + monStr2 + "-" + dayStr2
      dataObj2.day = dayStr2
      dataObj2.thisDay = this_day
      dateArr.push(dataObj2)
      i++;
      date1.setDate(date1.getDate() + 1);
    } 
    this.setData({
      weeks_data: dateArr
    })
    for (var i in this.data.weeks_data) {
      if (this.data.weekObj.time === this.data.weeks_data[i].datas) {
        this.setData({
          activeIndex: i
        })
        console.log(this.data.activeIndex)
      }
    }
  },
  //日期拼接
  transferDate: function (date) {
    var yearTemp = date.getFullYear()
    var monthTemp = date.getMonth() + 1
    var dayTemp = date.getDate()
    if (parseInt(monthTemp) < 10) {
      monthTemp = "0" + monthTemp
    }
    if (parseInt(dayTemp) < 10) {
      dayTemp = "0" + dayTemp
    }
    return yearTemp + "-" + monthTemp + "-" + dayTemp;
  },

  //日期段
  dataMiddle: function (datestr) {
    var tempDate = new Date()
    var list = datestr.split("-")
    tempDate.setFullYear(list[0])
    tempDate.setMonth(list[1] - 1)
    tempDate.setDate(list[2])
    return tempDate
  },
  //获取本周安排
  weekList: function (dataType) {
    let self = this
    let timeObj = self.data.weekObj
    if (dataType) {
      timeObj.time = dataType.currentTarget.dataset.day
      self.setData({
        activeIndex: dataType.currentTarget.id
      })
    }
    app.query("web/orders/calendar_orders", timeObj).then(res => {
      if (res.code === 200) {
        // console.log(res)
        self.setData({
          scheduleList: formatData(res.orders)
        })
        console.log(self.data.scheduleList)
      }
    })
  },
  //获取订单列表
  transportList:function(){
    let self = this
    console.log(self.data.type)
    app.query("web/users/driver_orders", { type: self.data.type }).then(res => {
      if (res.code === 200) {
        console.log(res)
        let formatOrders = formatData(res.orders)
        self.setData({
          transportList: formatOrders,
        })
        self.weekList()
        console.log(self.data.transportList)
      }
    })
  },
  tabbar:function(e){
    this.setData({
      tabbarIndex: e.currentTarget.id,
    })
  },
  showInput: function () {
    this.setData({
      inputShowed: true
    });
  },
  hideInput: function () {
    this.setData({
      inputVal: "",
      inputShowed: false
    });
  },
  clearInput: function () {
    this.setData({
      inputVal: ""
    });
  },
  inputTyping: function (e) {
    this.setData({
      inputVal: e.detail.value
    });
  },
  dataTime: function () {
    let self = this
    let times = []
    let timeObj;
    var i, j, z
    var month = date.getMonth() + 1;
    for (i = month, j = 1; i > 0, j <= month; i-- , j++) {
      timeObj = {}
      timeObj.id = i;
      timeObj.name = this.convertToChinese(j) + "月";
      times.push(timeObj);
    }
    self.setData({
      yearsList: times
    })
    console.log(self.data.yearsList)
  },
  //数字转中文
  convertToChinese: function (num) {
    var n = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"]
    var str = num.toString()
    var len = num.toString().length
    var C_Num = []
    for (var i = 0; i < len; i++) {
      C_Num.push(n[str.charAt(i)])
    }
    return C_Num.join('')
  },
  //获取钱包列表
  moneyList: function (e) {
    this.setData({
      yearsIndex: e.currentTarget.id,
      pricesList:[]
    })
    let pricesArray = []
    let yeaesId = e.currentTarget.dataset.yearsid
    let detailObj = { start: yeaesId, end: yeaesId, limit: 1000, page: 1 }
    app.query("web/payments/payments_detail", detailObj).then(res => {
      let formatOrders = formatData(res.payments)
      this.setData({
        monyList: formatOrders
      })
      console.log(this.data.monyList)
    })
  },
  //星星判断
  stars: function () {
    let starsList = []
    let imgObj = { url: "../img/me/order_star.png" }
    if (this.data.user.raty != null) {
      this.data.user.raty = (parseInt(this.data.user.raty / 1))
      console.log(this.data.user.raty)
      switch (this.data.user.raty) {
        case 1: starsList.push(imgObj); break;
        case 2: starsList.push(imgObj, imgObj); break;
        case 3: starsList.push(imgObj, imgObj, imgObj); break;
        case 4: starsList.push(imgObj, imgObj, imgObj, imgObj); break;
        case 5: starsList.push(imgObj, imgObj, imgObj, imgObj, imgObj); break;
      }
      this.setData({
        monyStars: starsList
      })
      console.log(starsList)
    }
  },
  //详情
  mineDetail: function () {
    wx.navigateTo({
      url: '../mineDetail/mineDetail',
    })
  }
})